import { Button, Modal, message, Spin, Breadcrumb, Icon, Row, Col } from 'antd';
import { WeaTab, WeaErrorPage, WeaTools, WeaSearchGroup } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import equal from 'deep-equal';
import { Condition } from '../list/customCondition';
import CustomerContact from '../public/CustomerContact';
import ViewContacter from '../public/ViewContacter';
import AddContacterModal from '../dialog/AddContacterModal';
import ViewSellChance from '../public/ViewSellChance';
import LeaveMessage from '../public/CustomerMessage';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
let _that = '';
@observer
class CardManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
    _that = this;
  }
  componentDidMount() {
    const { contentStore, paramsData } = this.props;
    const { contactLogCondition, setParamsFromLeft } = contentStore;
    setParamsFromLeft(paramsData);

    contactLogCondition();
    this.rightMenuTab();
  }
  rightMenuTab() {
    const rightWidth = jQuery('.sellchancemain-right-tab').width();
    if (rightWidth < 680) {
      jQuery('.sellchancemain-right-tab .wea-input-focus').hide();
      jQuery('.crm-wea-new-top-req-wapper .sellchancemain-right-tab .wea-search-tab .ant-btn').css({ borderRadius: 0, borderLeft: '1px solid #d9d9d9' });
    } else {
      jQuery('.sellchancemain-right-tab .wea-input-focus').show();
    }
  }
  componentWillReceiveProps(nextProps) {
    const { contentStore } = this.props;
    if (!equal(this.props.rightInfos, nextProps.rightInfos)) {
      contentStore.setTabKey('1');
    }
    const oldCusid = this.props.paramsData.customerId;
    const newCusid = nextProps.paramsData.customerId;

    const oldChanceid = this.props.paramsData.sellchanceId;
    const newChanceid = nextProps.paramsData.sellchanceId;
    if (oldCusid != newCusid || oldChanceid != newChanceid) {
      const { contentStore, paramsData } = nextProps;
      const { contactLogCondition, setParamsFromLeft } = contentStore;
      setParamsFromLeft(paramsData);
      this.rightMenuTab();
    }
  }

  render() {
    const { contentStore, rightInfos, type, paramsData } = this.props;
    const { selectTabKey, showSearchAd, setShowSearchAd, highSearchParamsAd, doSearch, manageCondition, form, mineCrmContactStore, customerId, formParams, contacterCardData, contacterCardTotal,
      sellChanceCardData, sellChanceCardDataTotal, crmMessageStore } = contentStore;
    return (
      <div className="crm-right-tab">
        <div className="sellchancemain-right-top">
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@4tj9rr`} >
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@rot4ez`} span="20">
              <Breadcrumb ecId={`${this && this.props && this.props.ecId || ''}_Breadcrumb@073hzt`}>
                {
                  rightInfos.titleInfo && rightInfos.titleInfo.sellChanceNameHtml ?
                    <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@tflqbv`}><span dangerouslySetInnerHTML={{ __html: rightInfos.titleInfo.sellChanceNameHtml }} /></Breadcrumb.Item>
                    : <div />
                }
                <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@rnsgdr`}><span dangerouslySetInnerHTML={{ __html: rightInfos.titleInfo && rightInfos.titleInfo.crmNameHtml }} /></Breadcrumb.Item>
                <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@0ktc8q`}><span dangerouslySetInnerHTML={{ __html: rightInfos.titleInfo && rightInfos.titleInfo.managerNameHtml }} /></Breadcrumb.Item>
              </Breadcrumb>
            </Col>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4qvcug`} span="4">
              {
                selectTabKey == '2' &&
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lqkh08`} title={getLabel(1421, '新增')} size="small" type="primary" onClick={() => this.AddContacter()}>{getLabel(82, '新建') + getLabel(572, '联系人')}</Button>
              }
            </Col>
          </Row>
        </div>
        <div className="sellchancemain-right-tab">
          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@db1z17`}
            buttonsAd={this.getTabButtonsAd(this.props.ecId || '')} // 高级搜索底部button
            searchType={['base', 'advanced']}
            {...this.getHighSearchs()}
            setShowSearchAd={(bool) => { setShowSearchAd(bool); }}
            hideSearchAd={() => setShowSearchAd(false)}
            showSearchAd={showSearchAd}
            onSearch={(v) => { doSearch(); }}
            selectedKey={selectTabKey}
            datas={toJS(rightInfos.tabInfo)}
            keyParam="key"
            onChange={this.changeTab.bind(this)}
            searchsAd={
              <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@3brxth`} condition={manageCondition || []} form={form} onEnterSearch={this.onEnterSearch} /></div>
            }
          />
        </div>
        {
          selectTabKey == '1' &&
          <div className="contact-logs-container">
            <CustomerContact ecId={`${this && this.props && this.props.ecId || ''}_CustomerContact@a65xbl`} type={type} contentStore={mineCrmContactStore} params={{ ...paramsData, ...formParams }} />
          </div>
        }
        {
          selectTabKey == '2' &&
          <div className="contact-logs-container">
            <ViewContacter ecId={`${this && this.props && this.props.ecId || ''}_ViewContacter@0lg05x`} data={toJS(contacterCardData)} total={contacterCardTotal} pageChange={(num) => { contentStore.getContacterInfo({ pageNum: num }); }} />
          </div>
        }
        {
          selectTabKey == '3' &&
          <div className="contact-logs-container">
            <LeaveMessage ecId={`${this && this.props && this.props.ecId || ''}_LeaveMessage@cc8w19`} ref="leaveMessage" contentStore={crmMessageStore} params={{ from: 'mine', customerId: rightInfos.customerId, ...formParams }} />
          </div>
        }
        {
          selectTabKey == '4' &&
          <div className="contact-logs-container">
            <ViewSellChance ecId={`${this && this.props && this.props.ecId || ''}_ViewSellChance@1q0ehh`} data={toJS(sellChanceCardData)} total={sellChanceCardDataTotal} pageChange={(num) => { contentStore.getSellChanceInfo({ pageNum: num }); }} />
          </div>
        }
        {
          selectTabKey == '2' &&
          <AddContacterModal ecId={`${this && this.props && this.props.ecId || ''}_AddContacterModal@w7c69u`} ref="addContacterModal" customerId={rightInfos.customerId} contentStore={contentStore} onSave={(params) => { contentStore.saveContacter(params); }} />
        }
      </div>
    );
  }
  changeTab(key) {
    const { contentStore } = this.props;
    const { setTabKey } = contentStore;
    // const { actions, paramsData } = this.props;
    setTabKey(key);
    // actions.setParamsFromLeft(paramsData);
  }
  getTabButtonsAd(ecId) {
    const { contentStore } = this.props;
    const { setShowSearchAd, clearFormFields, doSearch } = contentStore;
    return [
      (<Button ecId={`${ecId}_Button@rxnbeh@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${ecId}_Button@m2lbmx@reset`} type="ghost" onClick={() => { clearFormFields(); }}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${ecId}_Button@1g7sn4@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
    ];
  }
  getHighSearchs() {
    const { contentStore } = this.props;
    const { selectTabKey, form, appendFormFields } = contentStore;
    const formParams = form.getFormParams();
    if (selectTabKey == '1') {
      return {
        searchsBaseValue: formParams.remark,
        buttons: [''],
        onSearchChange: (v) => { appendFormFields({ remark: { value: v } }); },
      };
    }
    if (selectTabKey == '2') {
      return {
        searchsBaseValue: formParams.firstname,
        buttons: [],
        onSearchChange: (v) => { appendFormFields({ firstname: { value: v } }); },
      };
    }
    if (selectTabKey == '3') {
      return {
        searchsBaseValue: formParams.remarkM,
        buttons: [''],
        onSearchChange: (v) => { appendFormFields({ remarkM: { value: v } }); },
      };
    }
    if (selectTabKey == '4') {
      return {
        searchsBaseValue: formParams.subject,
        buttons: [''],
        onSearchChange: (v) => { appendFormFields({ subject: { value: v } }); },
      };
    }
  }
  getSearchsCondotion() {
    const { contactLogCondition, contacterCardCondition, leaveMessageCondition, sellchanceCardCondition, selectTabKey } = this.props;
    let highCondition = [];
    if (selectTabKey == '1') {
      highCondition = contactLogCondition.toJS();
    } else if (selectTabKey == '2') {
      highCondition = contacterCardCondition.toJS();
    } else if (selectTabKey == '3') {
      highCondition = leaveMessageCondition.toJS();
    } else if (selectTabKey == '4') {
      highCondition = sellchanceCardCondition.toJS();
    }
    const group = [];
    highCondition.map((c,indexGroup) => {
      const items = [];
      c.items.map((field,index) => {
        items.push({
          com: (<FormItem
            ecId={`${this && this.props && this.props.ecId || ''}_FormItem@1423tl@${index}`}
            label={`${field.label}`}
            labelCol={{ span: `${field.labelcol}` }}
            wrapperCol={{ span: `${field.fieldcol}` }}
          >
            {WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
          </FormItem>),
          colSpan: 1,
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@zyvhya@${indexGroup}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} col={1} />);
    });
    return group;
  }
    AddContacter = () => {
      const { contentStore } = this.props;
      contentStore.addContacterForm({ operation: 'add' });
      this.refs.addContacterModal.setVisible(true);
    }

    onEnterSearch=() => {
      const { contentStore } = this.props;
      contentStore.doSearch();
      contentStore.setShowSearchAd(false);
    }
}

class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== '';
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@eps6pi`} msg={hasErrorMsg ? this.props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />
    );
  }
}

CardManage = WeaTools.tryCatch(React, MyErrorHandler, { error: '' })(CardManage);

jQuery(window).resize(() => {
  _that && _that.rightMenuTab && _that.rightMenuTab();
});

export default CardManage;

